/**
 * @program: LeetCode
 * @description: LeetCode :
 * @author: WXY
 * @create: 2023-01-12 17:38
 * @Version 1.0
 **/
public class offer_twentysix3_mergeKLists {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        return mergeSort(lists, 0, lists.length - 1);
    }

    private ListNode mergeSort(ListNode[] lists, int left, int right) {
        if (left >= right) return lists[left];
        int mid = (left + right) / 2;
        ListNode leftNode = mergeSort(lists, left, mid);
        ListNode rightNode = mergeSort(lists, mid + 1, right);
        return merge(leftNode, rightNode);
    }

    private ListNode merge(ListNode left, ListNode right) {
        ListNode p = new ListNode(), node = p;
        while (left != null && right != null) {
            if (left.val < right.val) {
                p.next = left;
                left = left.next;
            } else {
                p.next = right;
                right = right.next;
            }
            p = p.next;
        }
        p.next = left == null ? right : left;
        return node.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
